package com.zzyl.web.task;

import cn.hutool.core.collection.CollectionUtil;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.mapper.ContractMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import static com.zzyl.common.constant.CacheConstants.CONTRACT_KEY;
import java.time.LocalDateTime;
import java.util.List;


@Component
@RequiredArgsConstructor
public class Task {
    private final ContractMapper contractMapper;
    private final RedisTemplate<Object,Object> redisTemplate;
    @Scheduled(cron = "0 0 1 * * ?")
    public void executeTask() {

        //获取缓存里的Contract集合
        List<Contract> list = (List<Contract>) redisTemplate.opsForValue().get(CONTRACT_KEY);
        if(CollectionUtil.isNotEmpty(list)){
            assert list != null;
            taskContract(list);

        }
        else {
            //缓存没有直接从数据库拿
            list=contractMapper.selectContractAll();
            taskContract(list);
        }
    }
    // 任务执行逻辑
    private void taskContract(List<Contract> list) {
        List<Contract> listNew= list.stream()
                .filter(contract -> {//过滤出来需要修改状态的contract
                    LocalDateTime now = LocalDateTime.now();
                    return contract.getStartDate() != null &&
                            contract.getEndDate() != null &&
                            !now.isBefore(contract.getStartDate()) &&
                            now.isBefore(contract.getEndDate());
                }).toList();
        listNew.forEach(contract -> {//遍历上面过滤出来的，修改状态然后修改数据库
            contract.setStatus(1);
            contractMapper.updateContract(contract);
        });
        //更新最新缓存
        list=contractMapper.selectContractAll();
        redisTemplate.opsForValue().set(CONTRACT_KEY,list);
    }
}
